package controller

import (
	"encoding/json"
	erp "ez/apps/erp/document"
	"ez/apps/flow/auto/controller"
	flow "ez/apps/flow/document"
	"ez/config/code"
	"ez/custom/cc"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type FlowingController struct {
	controller.FlowingAutoController
}

func init() {
	c := &FlowingController{}
	c.SetRouteParam("/flow", "/admin", "Flowing")
	ez.CreateApi(c.AdminGet(), c.GetAction)
	ez.CreateApi(c.AdminList(), c.ListAction)
	ez.CreateApi(c.AdminSave(), c.SaveAction)
	ez.CreateApi(c.AdminCopy(), c.CopyAction)
	ez.CreateApi(c.AdminUpdate(), c.UpdateAction)
	ez.CreateApi(c.AdminChoice(), c.ChoiceAction)
	ez.CreateApi(c.AdminDelete(), c.DeleteAction)
	ez.CreateApi(c.AdminUnDelete(), c.UnDeleteAction)
	ez.CreateApi(c.AdminDestroy(), c.DestroyAction)
	ez.CreateApi(c.AdminUpdateMany(), c.UpdateManyAction)
	ez.CreateApi(c.AdminDeleteMany(), c.DeleteManyAction)
	ez.CreateApi(c.AdminDestroyMany(), c.DestroyManyAction)
	ez.CreateApi(c.AdminApi("/Flowing/start"), c.StartAction)
	ez.CreateApi(c.AdminApi("/Flowing/submit"), c.SubmitAction)
	ez.CreateApi(c.AdminApi("/Flowing/auth"), c.AuthAction)
	ez.CreateApi(c.AdminApi("/Flowing/reset"), c.ResetAction)
}

// func (c FlowingController) AccessControl(session *ez.Session) { /* 在这里面重构 */ }
// func (c FlowingController) GetAction(session *ez.Session) { /* 在这里面重构 */ }
// func (c FlowingController) ListAction(session *ez.Session) { /* 在这里面重构 */ }
func (c FlowingController) StartAction(session *ez.Session) {
	this := cc.New(session)
	id := this.Get("id").IsInt64()
	flowId := this.Get("flowId").IsInt64()
	ownerId := this.Get("ownerId").IsInt64()
	targetType := this.Get("type").IsString("")
	title := this.Get("title").IsString("默认评审流程")
	flowingCrud := flow.NewFlowCrud()
	fl, _ := flowingCrud.FindId(flowId)
	if len(fl.Points) == 0 {
		this.ReturnError(code.Error, "流程设计有误", "")
		return
	}

	flowing := new(flow.Flowing)
	flowing.FlowCur = fl.Points[0]
	flowing.Owner = ownerId
	flowing.FlowId = flowId
	flowing.Title = title
	flowing.TargetId = id
	flowing.TargetType = targetType
	flowing.Save()
	this.ReturnSuccess("OK", flowing)
}
func (c FlowingController) ResetAction(session *ez.Session) {

	this := cc.New(session)
	id := this.Get("id").IsInt64()

	flowing, e := flow.NewFlowingCrud(session).FindId(id)

	if this.Try(e) {
		return
	}
	flowing.IsCancel = false
	flowing.IsConfirm = false
	flowing.State = "管理员解锁重置"
	flowing.SetFactoryParams(session).SetEvent(true)

	if this.Try(flowing.Save()) {
		return
	}
	this.ReturnSuccess("数据重置成功", flowing)
}
func (c FlowingController) SubmitAction(session *ez.Session) {
	this := cc.New(session)
	flowing := new(flow.Flowing)
	if this.Try(this.FillJson(&flowing)) {
		return
	}
	//默认数据处理
	if flowing.FlowCur == nil {
		this.ReturnError(code.Error, "系统错误：", "")
		return
	}
	flowing.FlowCur.FillAt = time.Now()

	orgFlowing, e := flow.NewFlowingCrud(session).FindId(flowing.Id)
	if orgFlowing.IsConfirm {
		this.ReturnError(code.Error, "审批已完成", "")
		return
	}
	if orgFlowing.IsCancel {
		this.ReturnError(code.Error, "审批已取消", "")
		return
	}

	orgFlowing.LoadFlow()
	if this.Try(e) {
		return
	}
	finalState := flowing.FlowCur.FinalState
	switch finalState {
	case "通过":
	case "驳回":
	case "取消":
		//取消操作
		orgFlowing.IsCancel = true
		orgFlowing.State = "审批流程已取消"
		orgFlowing.Flows = append([]*flow.FLowPoint{flowing.FlowCur}, orgFlowing.Flows...)
		orgFlowing.GetFactory().SetEventOn()
		if this.Try(orgFlowing.Save()) {
			return
		}

		this.ReturnSuccess("OK", orgFlowing)
		return
	case "完成":
		orgFlowing.IsConfirm = true
		orgFlowing.ConfirmAt = time.Now()
		orgFlowing.State = "审批流程已完成"
		orgFlowing.Flows = append([]*flow.FLowPoint{flowing.FlowCur}, orgFlowing.Flows...)
		orgFlowing.GetFactory().SetEventOn()
		if this.Try(orgFlowing.Save()) {
			return
		}
		this.ReturnSuccess("OK", orgFlowing)
		return
		//完结操作
	default:
	}
	orgFlowing.Flows = append([]*flow.FLowPoint{flowing.FlowCur}, orgFlowing.Flows...)

	noNextFount := true
	for index, flow := range orgFlowing.Flow.Points {
		if flow.Key == flowing.FlowCur.FlowTo {
			orgFlowing.FlowCur = flow
			orgFlowing.Index = int64(index)
			orgFlowing.State = flow.Name
			noNextFount = false
		}
	}

	if noNextFount {
		//检查是否是最后一个工序，如果是，正常完结
		//如果不是默认进入下一个
		if orgFlowing.Index == int64(len(orgFlowing.Flow.Points)-1) {
			//是最后一个工序
			orgFlowing.ConfirmAt = time.Now()
			orgFlowing.IsConfirm = true
			orgFlowing.State = "审批流程通过 [ 结束 ]"
		} else {
			orgFlowing.Index++
			orgFlowing.FlowCur = orgFlowing.Flow.Points[orgFlowing.Index]
			orgFlowing.State = orgFlowing.FlowCur.Name
		}

	}
	orgFlowing.GetFactory().SetEventOn()
	if this.Try(orgFlowing.Save()) {
		return
	}

	this.ReturnSuccess("OK", orgFlowing)
}
func (c FlowingController) AuthAction(session *ez.Session) {
	this := cc.New(session)
	id := this.Get("id").IsInt64()
	//auth := ss.M{}
	flowing, err := flow.NewFlowingCrud(session).FindId(id)
	if this.Try(err) {
		return
	}
	//flows := service.GetFlowById(need.Flow)
	var authModel struct {
		Auth struct {
			User []struct {
				Id   int64  `json:"id" bson:"id"`
				Name string `json:"name" bson:"name"`
			} `json:"user"`
			Department []struct {
				Id   int64  `json:"id" bson:"id"`
				Name string `json:"name" bson:"name"`
			} `json:"department"`
		} `json:"auth"`
	}
	content, err := json.Marshal(flowing.FlowCur)
	if this.Try(err) {
		return
	}
	err = json.Unmarshal(content, &authModel)
	if this.Try(err) {
		return
	}
	//检查用户是否具有权限
	uid := this.GetUserId()
	emp, err := erp.NewEmpCrud(session).FindId(uid)

	userAccess := false
	departmentAccess := false
	for _, u := range authModel.Auth.User {
		if u.Id == uid {
			userAccess = true
		}
	}
	for _, dept := range authModel.Auth.Department {
		if dept.Id == emp.DepartmentId {
			departmentAccess = true
		}
	}
	editAccess := false
	if flowing.Owner == uid {
		editAccess = true
	}

	this.ReturnSuccess("OK", ss.M{
		"userAccess":       userAccess,
		"departmentAccess": departmentAccess,
		"editAccess":       editAccess,
		"isSuperAdmin":     uid == 1,
	})
}
